Serialize Dictionary with a string key and List[] value to JSON

Posted by Patrick on Stack Overflow See other posts from Stack Overflow or by Patrick
Published on 2010-04-12T14:40:15Z Indexed on 2010/04/12 14:43 UTC
Read the original article Hit count: 224

Filed under:
|
|
|
|

How can I serialize a python Dictionary to JSON and pass back to javascript, which contains a string key, while the value is a List (i.e. [])

if request.is_ajax() and request.method == 'GET':

groupSet = GroupSet.objects.get(id=int(request.GET["groupSetId"])) groups = groupSet.groups.all()

group_items = [] #list groups_and_items = {} #dictionary

for group in groups: group_items.extend([group_item for group_item in group.group_items.all()]) #use group as Key name and group_items (LIST) as the value groups_and_items[group] = group_items

data = serializers.serialize("json", groups_and_items)

return HttpResponse(data, mimetype="application/json")

the result: [{"pk": 5, "model": "myApp.group", "fields": {"name": "\u6fb4\u9584", "group_items": [13]}}]

while the group_items should have many group_item and each group_item should have "name", rather than only the Id, in this case the Id is 13.

I need to serialize the group name, as well as the group_item's Id and name as JSON and pass back to javascript.

I am new to Python and Django, please advice me if you have a better way to do this, appreciate. Thank you so much. :)

© Stack Overflow or respective owner

Related posts about django

Related posts about python